<template>
  <div class="accommodation-detail">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="luxury-spinner">
        <div class="spinner-bar"></div>
        <p>Loading...</p>
      </div>
    </div>

    <!-- 主内容区 -->
    <div v-else class="luxury-content-wrapper">
      <!-- 酒店标题 -->
      <div class="hotel-header">
        <h1 class="hotel-title">{{ hotelName }}</h1>
        <p class="hotel-subtitle">精选房型，舒适体验</p>
      </div>

      <!-- 房型选择器 -->
      <div class="room-type-selector-wrapper">
        <div class="selector-label">
          <i class="el-icon-s-grid"></i>
          <span>选择房型</span>
        </div>
        <el-select
          v-model="selectedRoomType"
          placeholder="请选择房型"
          class="hoshino-select"
          @change="filterRoomsByType"
          popper-class="hoshino-select-dropdown"
        >
          <el-option
            v-for="(type, index) in uniqueRoomTypes"
            :key="index"
            :label="type"
            :value="type"
          />
        </el-select>
      </div>

      <!-- 房型列表 -->
      <div class="room-types-container">
        <div v-for="(roomType, index) in filteredGroupedRooms" :key="index" class="room-type-section">
          <div class="room-type-header">
            <h2 class="room-type-title">{{ roomType.type }}</h2>
            <div class="room-type-divider"></div>
          </div>

          <div class="room-list">
            <div v-for="(room, roomIndex) in roomType.rooms" :key="roomIndex" class="room-card">
              <!-- 房间图片 -->
              <div class="room-image">
                <image-preview :src="room.imageUrl" :width="800" :height="400" />
              </div>

              <!-- 房间信息 -->
              <div class="room-info">
                <h3 class="room-name">{{ room.name }}</h3>
                <div class="room-meta">
                  <div class="meta-item">
                    <i class="el-icon-money"></i>
                    <span>价格: ¥{{ room.price }} /晚</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-s-home"></i>
                    <span>面积: {{ room.square }} ㎡</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-user-solid"></i>
                    <span>容纳: {{ room.maxGuests }} 人</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-s-check"></i>
                    <span>可订: {{ room.currentNumsRoom }} 间</span>
                  </div>
                </div>

                <!-- 房间描述 -->
                <div class="room-description">
                  <p>{{ room.description }}</p>
                </div>

                <!-- 房间设施 -->
                <div class="room-facilities">
                  <h4>房间设施</h4>
                  <div class="facility-tags">
                    <span v-for="(facility, facIndex) in parseFacilities(room.device)" :key="facIndex" class="facility-tag">
                      {{ facility }}
                    </span>
                  </div>
                </div>

                <!-- 预订按钮 -->
                <div class="room-actions">
                  <el-button
                    type="primary"
                    class="book-button"
                    @click="handleBook(room)"
                    :disabled="room.currentNumsRoom <= 0"
                  >
                    {{ room.currentNumsRoom <= 0 ? '已售罄' : '立即预订' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getAccommodationByDeptId } from '@/api/system/accommodation';
  import { addOrder } from '@/api/system/order';
  import ImagePreview from '@/components/ImagePreview';

  export default {
    name: 'AccommodationDetail',
    components: {
      ImagePreview
    },
    data() {
      return {
        deptId: null,
        hotelName: '',
        rooms: [],
        groupedRooms: [],
        filteredGroupedRooms: [],
        uniqueRoomTypes: [],
        selectedRoomType: null,
        isLoading: true
      };
    },
    created() {
      this.userId = this.$store.state.id;
      this.deptId = this.$route.params.deptId || this.$route.query.deptId;
      if (!this.deptId) {
        this.$message.error('参数错误: 缺少酒店ID');
        this.$router.go(-1);
        return;
      }
      this.fetchAccommodationData();
    },
    methods: {
      async fetchAccommodationData() {
        this.isLoading = true;
        try {
          const response = await getAccommodationByDeptId(this.deptId);
          if (response.code === 200 && response.data?.length > 0) {
            this.rooms = response.data;
            this.hotelName = response.data[0]?.hotel?.deptName || '未知酒店';
            this.groupRoomsByType();
            this.extractUniqueRoomTypes();

            // 默认选择第一个房型
            if (this.uniqueRoomTypes.length > 0) {
              this.selectedRoomType = this.uniqueRoomTypes[0];
              this.filterRoomsByType();
            }
          } else {
            this.$message.warning('该酒店暂无房型信息');
          }
        } catch (error) {
          console.error('获取房型详情失败:', error);
          this.$message.error('获取房型详情失败');
        } finally {
          this.isLoading = false;
        }
      },

      groupRoomsByType() {
        const typeMap = {};
        this.rooms.forEach(room => {
          if (!room.roomType) return;
          if (!typeMap[room.roomType]) {
            typeMap[room.roomType] = {
              type: room.roomType,
              rooms: []
            };
          }
          typeMap[room.roomType].rooms.push(room);
        });
        this.groupedRooms = Object.values(typeMap);
      },

      extractUniqueRoomTypes() {
        const types = new Set();
        this.rooms.forEach(room => {
          if (room.roomType) types.add(room.roomType);
        });
        this.uniqueRoomTypes = Array.from(types);
      },

      filterRoomsByType() {
        if (!this.selectedRoomType) {
          this.filteredGroupedRooms = [];
          return;
        }
        this.filteredGroupedRooms = this.groupedRooms.filter(
          group => group.type === this.selectedRoomType
        );
      },

      parseFacilities(deviceStr) {
        if (!deviceStr) return [];
        return deviceStr.split(/[；。,.、]/)
          .filter(fac => fac.trim())
          .map(fac => fac.trim());
      },

      // 直接预订房间
      async handleBook(room) {
        if (room.currentNumsRoom <= 0) {
          this.$message.warning('该房型已售罄');
          return;
        }

        try {
          const orderData = {
            userId: this.userId,
            productId: room.id,
            productType: "住宿",
            deptId: this.deptId,
            quantity: 1,
            unitPrice: room.price,
            totalPrice: room.price,
            status: "待支付"
          };

          // 调用单个订单创建API
          const response = await addOrder(orderData);

          if (response.code === 200) {
            this.$message.success('预订成功，请在订单中心完成支付');
            // 刷新房间数据
            this.fetchAccommodationData();
          } else {
            this.$message.error('预订失败: ' + response.msg);
          }
        } catch (error) {
          console.error('预订失败:', error);
          this.$message.error('预订失败: ' + error.message);
        }
      }
    }
  };
</script>

<style scoped>
  /* 整体布局 */
  .accommodation-detail {
    font-family: "游明朝", YuMincho, "ヒラギノ明朝 ProN W3", "Hiragino Mincho ProN", serif;
    background-color: #faf9f7;
    min-height: 100vh;
    padding: 40px 0;
  }

  /* 加载动画 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.9);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .luxury-spinner {
    text-align: center;
  }

  .spinner-bar {
    width: 80px;
    height: 2px;
    background: linear-gradient(90deg, transparent, #c0a080, transparent);
    margin: 0 auto 15px;
    position: relative;
    overflow: hidden;
  }

  .spinner-bar::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 30px;
    height: 100%;
    background: #c0a080;
    animation: loading 1.5s infinite ease-in-out;
  }

  @keyframes loading {
    0% { transform: translateX(-30px); }
    100% { transform: translateX(110px); }
  }

  .luxury-spinner p {
    color: #8c7c68;
    font-size: 0.9rem;
    letter-spacing: 3px;
    text-transform: uppercase;
  }

  /* 内容容器 */
  .luxury-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  /* 酒店头部 */
  .hotel-header {
    text-align: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e8e1d7;
  }

  .hotel-title {
    font-size: 2.5rem;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;
    letter-spacing: 1px;
  }

  .hotel-subtitle {
    font-size: 1.1rem;
    color: #8c7c68;
    margin: 0 0 15px;
  }

  /* 房型选择器 - 重新设计 */
  .room-type-selector-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 30px auto 40px;
    padding: 15px 0;
    border-top: 1px solid #e8e1d7;
    border-bottom: 1px solid #e8e1d7;
    max-width: 800px;
  }

  .selector-label {
    display: flex;
    align-items: center;
    margin-right: 15px;
    font-size: 1.1rem;
    color: #5d493f;
  }

  .selector-label i {
    margin-right: 8px;
    color: #c0a080;
    font-size: 1.3rem;
  }

  .hoshino-select {
    width: 300px;
  }

  /* 房型分类 */
  .room-types-container {
    margin-top: 20px;
  }

  .room-type-section {
    margin-bottom: 60px;
  }

  .room-type-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
  }

  .room-type-title {
    font-size: 1.8rem;
    color: #555;
    margin-right: 20px;
    white-space: nowrap;
  }

  .room-type-divider {
    flex-grow: 1;
    height: 1px;
    background: #e8e1d7;
  }

  /* 房间列表 */
  .room-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
    gap: 40px;
  }

  .room-card {
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
  }

  .room-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
  }

  /* 房间图片 */
  .room-image {
    height: 300px;
    overflow: hidden;
  }

  .room-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.6s ease;
  }

  .room-card:hover .room-image img {
    transform: scale(1.05);
  }

  /* 房间信息 */
  .room-info {
    padding: 30px;
  }

  .room-name {
    font-size: 1.6rem;
    color: #333;
    margin-bottom: 20px;
    position: relative;
    padding-bottom: 15px;
  }

  .room-name::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 50px;
    height: 2px;
    background: #c0a080;
  }

  .room-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 25px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 0.95rem;
  }

  .meta-item i {
    margin-right: 8px;
    color: #c0a080;
    font-size: 1.2rem;
  }

  /* 房间描述 */
  .room-description {
    margin-bottom: 25px;
    color: #666;
    line-height: 1.8;
    font-size: 0.95rem;
  }

  /* 房间设施 */
  .room-facilities h4 {
    font-size: 1.1rem;
    color: #555;
    margin-bottom: 15px;
  }

  .facility-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .facility-tag {
    background-color: #f5f0ea;
    color: #8c7c68;
    padding: 6px 15px;
    border-radius: 20px;
    font-size: 0.85rem;
    letter-spacing: 0.5px;
  }

  /* 预订按钮 */
  .room-actions {
    margin-top: 30px;
    text-align: right;
  }

  .book-button {
    background-color: #c0a080;
    border-color: #c0a080;
    color: #fff;
    padding: 12px 35px;
    font-size: 1rem;
    letter-spacing: 1px;
    border-radius: 4px;
    transition: all 0.3s ease;
  }

  .book-button:hover {
    background-color: #a08060;
    border-color: #a08060;
    transform: translateY(-2px);
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .room-list {
      grid-template-columns: 1fr;
    }

    .hotel-title {
      font-size: 2.2rem;
    }
  }

  @media (max-width: 768px) {
    .luxury-content-wrapper {
      padding: 0 15px;
    }

    .hotel-title {
      font-size: 2rem;
    }

    .room-info {
      padding: 20px;
    }

    .room-image {
      height: 250px;
    }

    .room-type-selector-wrapper {
      flex-direction: column;
      align-items: flex-start;
    }

    .selector-label {
      margin-bottom: 10px;
    }
  }

  @media (max-width: 576px) {
    .hotel-title {
      font-size: 1.8rem;
    }

    .room-type-title {
      font-size: 1.5rem;
    }

    .room-name {
      font-size: 1.4rem;
    }

    .hoshino-select {
      width: 100%;
    }
  }
</style>

<style>
  /* 全局下拉框样式 */
  .hoshino-select .el-input__inner {
    background-color: #f5f0ea;
    border: 1px solid #d8cbb9;
    border-radius: 4px;
    color: #5d493f;
    height: 44px;
    line-height: 44px;
    font-family: "游明朝", YuMincho, serif;
    padding: 0 15px;
  }

  .hoshino-select .el-input__inner:focus {
    border-color: #c0a080;
  }

  .hoshino-select .el-input__suffix {
    display: flex;
    align-items: center;
    right: 10px;
  }

  .hoshino-select .el-select__caret {
    color: #c0a080;
  }

  /* 下拉菜单样式 */
  .hoshino-select-dropdown {
    border: 1px solid #d8cbb9;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .hoshino-select-dropdown .el-select-dropdown__item {
    color: #5d493f;
    font-family: "游明朝", YuMincho, serif;
    height: 40px;
    line-height: 40px;
    padding: 0 15px;
  }

  .hoshino-select-dropdown .el-select-dropdown__item:hover {
    background-color: #f5f0ea;
  }

  .hoshino-select-dropdown .el-select-dropdown__item.selected {
    color: #c0a080;
    background-color: #faf9f7;
  }
</style>
